package com.stud.system.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.stud.common.exception.ServiceException;
import com.stud.common.mybatis.BaseServiceImpl;
import com.stud.common.utils.StringUtils;
import com.stud.common.utils.spring.SpringUtils;
import com.stud.system.domain.SysCacheInit;
import com.stud.system.mapper.SysCacheInitMapper;
import com.stud.system.service.CacheInitor;
import com.stud.system.service.SysCacheInitService;
import lombok.RequiredArgsConstructor;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.List;

/**
 * 缓存配置Service业务层处理
 *
 * @author Stud
 * @date 2023-03-25
 */
@Service
@RequiredArgsConstructor
public class SysCacheInitServiceImpl extends BaseServiceImpl<SysCacheInitMapper, SysCacheInit> implements SysCacheInitService {
    private final SysCacheInitMapper sysCacheInitMapper;

    @Async
    public void initCache() {
        LambdaQueryWrapper<SysCacheInit> queryWrapper = Wrappers.lambdaQuery();
        queryWrapper.eq(SysCacheInit::getInitFlag, 0);
        log.debug("查询需要初始化的缓存配置");
        List<SysCacheInit> cacheInits = sysCacheInitMapper.selectList(queryWrapper);
        if (CollectionUtils.isEmpty(cacheInits)) {
            log.debug("暂无需要初始化的缓存");
            return;
        }
        for (SysCacheInit cacheInit : cacheInits) {
            initCacheByClassName(cacheInit.getClassName());
        }
    }

    @Async
    public void initCacheByClassName(String className) {
        if (StringUtils.isBlank(className)) {
            throw new ServiceException("类名参数不可为空");
        }
        CacheInitor cacheInitor = SpringUtils.getBean(className);
        cacheInitor.initCache();
    }

}
